<?php
namespace App\Services\Core\Store\Hengchang;

use App\Services\Core\Store\Hengchang\HengchangConfig;
/**
 * 恒昌众鼎接口加密
 */
class AESUtils
{
    /**
     * HmacSHA256加密
     */
    public static function HmacSHA256($data)
    {
        $pass = hash_hmac('sha256',utf8_encode($data),utf8_encode(HengchangConfig::HENGCHANG_ENCRYPT),true);
        $password = base64_encode($pass);
        return $password;
    }
    /**
     * 算法/模式/填充：AES/CBC/PKCS5Padding
     */
        //获取APPSECRET
         static $appsecret = HengchangConfig::HENGCHANG_DE;
        //获取偏移量
         static $vi = HengchangConfig::HENGCHANG_VI;
        /**
         * 加密
         */
        public static function encrypt($str)
        {
            $data = openssl_encrypt($str,"AES-128-CBC", HengchangConfig::HENGCHANG_ENCRYPT, OPENSSL_RAW_DATA, HengchangConfig::HENGCHANG_VI);
            return $data;
        }
        /**
        * 解密
        */
        public static function decrypt($str)
        {
            $strs =  openssl_decrypt(base64_decode($str),"AES-128-CBC",HengchangConfig::HENGCHANG_DE,OPENSSL_RAW_DATA,HengchangConfig::HENGCHANG_VI);
//            $str = self::pkcs5Unpad( $str );
            return $strs;
        }
        /**
         * bin2hex还原
         */
        public static function hex2bin($hexData)
        {
            $binData = '';
            for($i = 0; $i < strlen ( $hexData ); $i += 2)
            {
                $binData .= chr(hexdec(substr($hexData, $i, 2)));
            }
            return $binData;
        }

        /**
         * 进行PKCS5Padding操作
         */
        public static function pkcs5Pad($text,$blocksize)
        {
            $pad = $blocksize - (strlen ( $text ) % $blocksize);
            return $text . str_repeat ( chr ( $pad ), $pad );
        }

        public static function pkcs5Unpad($text)
        {
            $pad = ord ( $text {strlen ( $text ) - 1} );
            if ($pad > strlen ( $text ))
                return false;
            if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)
                return false;
            return substr ( $text, 0, - 1 * $pad );
        }
}